﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace DPortAck.ObjectModel
{
    public class MachinePortConnectionTest
    {
        private MachineConnectionTest _machine;
        private ProtocolType _protocolType = ProtocolType.Tcp;
        private SocketType _socketType = SocketType.Stream;

        public MachineConnectionTest Machine
        {
            get { return _machine; }
            set { _machine = value; }
        }

        public int Port { get; set; }

        public ProtocolType ProtocolType
        {
            get { return _protocolType; }
            set { _protocolType = value; }
        }

        public SocketType SocketType
        {
            get { return _socketType; }
            set { _socketType = value; }
        }

        public MachinePortConnectionTestResult Execute()
        {
            MachinePortConnectionTestResult result = new MachinePortConnectionTestResult(this);
            result.Succeded = false;

            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType, ProtocolType))
            {
                s.ReceiveTimeout = 1;
                s.SendTimeout = 1;

                Console.Write("{0} - {1} - {2}... ", _machine.Test, _machine.Host, this);

                try
                {
                    IAsyncResult connectResult = s.BeginConnect(_machine.Host, Port, null, null);

                    connectResult.AsyncWaitHandle.WaitOne(_machine.Test.Timeout, true);

                    if (s.Connected)
                        result.Succeded = true;
                }
                catch (Exception ex)
                {
                    result.Exception = ex;
                }
            }

            string resultText = (result.Succeded) ? "ok" : "##### FAIL #####";

            Console.WriteLine("{0}", resultText);

            return result;
        }

        public override string ToString()
        {
            return String.Format("{0}.{1}", _protocolType, Port);
        }
    }
}
